$(document).ready(function() {
	//弹出jquery ui模态框就绪
	$("#shoppingModal").dialog({
		autoOpen: false,
		modal: true,
		width: 800,
		buttons: {
			"提交订单": function() {
				var numberSUM = "",
					ID_sum = "",
					Number_sum = "",
					Money_sum = "",
					reg = /^[0-9]*$/,
					flag = false;
				$(".shopNum").each(function(n1, v1) {
					if (reg.test($(this).val())) {
						if($(this).val()==""){
							flag = false;
							return false;
						}else{
							flag = true;
							numberSUM += $(this).val() + ",";
						}
					} else {
						flag = false;
						return false;
					};
				});
				if (flag) {
					$(".typeInput").each(function() {
						if ($(this).val() !== "") {
							ID_sum += $(this).val() + ",";
						};
					});
					$(".shopNum").each(function() {
						Number_sum += $(this).val() + ",";
					});
					$(".shopMoney").each(function() {
						Money_sum += $(this).text() + ",";
					});
					//给隐藏input插入值
					if($("#orderFormShopping").parent().attr("dataid")=="undefined"){
						$("#Order_GuestID").val($("#shoppingName").val());
					}else{
						$("#Order_GuestID").val($("#orderFormShopping").parent().attr("dataid"));
					};
					
					if($("#orderFormShopping").parent().attr("valHide")=="snap"){
						//临时订单
						$.ajax({
							url: "/Handler/OrderHandler.ashx",
							type: "post",
							dataType: "json",
							data: {
								fun: "f_0003",
								//Order_GuestID: $("#Order_GuestID").val(),
								OrderProduct_ProductID: ID_sum.substr(0, ID_sum.length - 1),
								OrderProduct_Number: Number_sum.substr(0, Number_sum.length - 1),
								OrderProduct_Money: Money_sum.substr(0, Money_sum.length - 1)
							},
							success: function(msg) {
								if (msg.r_code == "1") {
									toastr.success(msg.r_info, '系统提示：');
									$("#orderFormShopping").parent().modal('hide');
									$("#orderFormShopping").parent().remove();
									if(msg.r_msg==undefined){
										//刷新页面
										setTimeout(function() {
											window.location.href = window.location.href;
										}, 1000);
									}else{
										bootbox.alert(msg.r_msg,function(){
											//刷新页面
											setTimeout(function() {
												window.location.href = window.location.href;
											}, 1000);
										});
									};
								}else if (msg.r_code == "0") {
									toastr.error(msg.r_info, '错误提示：');
								};
							}
						});
					}else{
						//新增订单
						$.ajax({
							url: "/Handler/OrderHandler.ashx",
							type: "post",
							dataType: "json",
							data: {
								fun: "f_0002",
								Order_GuestID: $("#Order_GuestID").val(),
								OrderProduct_ProductID: ID_sum.substr(0, ID_sum.length - 1),
								OrderProduct_Number: Number_sum.substr(0, Number_sum.length - 1),
								OrderProduct_Money: Money_sum.substr(0, Money_sum.length - 1)
							},
							success: function(msg) {
								if (msg.r_code == "1") {
									toastr.success(msg.r_info, '系统提示：');
									$("#orderFormShopping").parent().modal('hide');
									$("#orderFormShopping").parent().remove();
									if(msg.r_msg==undefined){
										//刷新页面
										setTimeout(function() {
											window.location.href = window.location.href;
										}, 1000);
									}else{
										bootbox.alert(msg.r_msg,function(){
											//刷新页面
											setTimeout(function() {
												window.location.href = window.location.href;
											}, 1000);
										});
									};
								}else if (msg.r_code == "0") {
									toastr.error(msg.r_info, '错误提示：');
								};
							}
						});
					};
					$(this).dialog("close");
				} else {
					toastr.error("请检查产品数量，必须是一个有效的数字", '<h4>错误提示：</h4>');
				};
			},
			"继续选购":function(){
			    $(this).dialog("close");
			}
		}
	});
	//点击购物车按钮事件
	$("#shoppingCart").click(function() {
		var flag = false;
		var checkedHTML = [];
		//循环隐藏的input传值框
		$(".typeInput").each(function(a, e) {
			if ($(this).val() !== "") { //如果value不为空
				var Money_sum = 0;
				flag = true;
				checkedHTML.push('<h4 class="text-success">' + $(e).data("datalist").select + '</h4>');
				checkedHTML.push('<table class="table table-bordered table-condensed table-hover">');
				checkedHTML.push('<thead><tr><th>产品编码</th><th>产品名称</th><th>产品价格</th><th>数量</th><th>总金额</th></tr></thead><tbody>');
				//循环每一个input传值框中 用,分隔开的数据
				$.each($(this).val().split(","), function(n, v) {
					checkedHTML.push('<tr><td>' + $(e).data("datalist").code.split(",")[n] + '</td>');
					checkedHTML.push('<td>' + $(e).data("datalist").name.split(",")[n] + '</td>');
					checkedHTML.push('<td class="shopMoney">' + $(e).data("datalist").money.split(",")[n] + '</td>');
					checkedHTML.push('<td><input class="shopNum input-mini" type="number" value="1"></td>');
					checkedHTML.push('<td class="allMoney"><span class="text-error">' + $(e).data("datalist").money.split(",")[n] + '</span></td>');
					Money_sum += parseFloat($(e).data("datalist").money.split(",")[n]);
				});

				checkedHTML.push('</tbody><tfoot><tr>');
				checkedHTML.push('<th class="total-label" colspan="4" style="text-align: right;">小计</th>');
				checkedHTML.push('<th class="total-amount">￥： <strong class="text-error sumMoney">' + Money_sum + '</strong></th>');
				checkedHTML.push('</tr></tfoot></table>');
			}
		});
		if (flag) {
			$("#shoppingModal").html(checkedHTML.join(""));
			//数量变化后 总金额变化事件
			var reg = /^[0-9]*$/;
			$(".shopNum").on("keyup",function(){
				if (reg.test($(this).val())) {
					var this_parent=$(this).parents("tr"),
						this_table=$(this).parents("table")

					this_parent.find(".allMoney").html('<span class="text-error">'+this_parent.find(".shopMoney").text()*$(this).val()+"</span>");
					var summoney=0;
					this_table.find(".allMoney").each(function(){
						summoney+=parseFloat($(this).text());
					});
					this_table.find(".sumMoney").text(summoney);
				};
			});
			//输入数量后价格变化
			$("#shoppingModal").dialog("open");
		} else {
			toastr.info("请先选择产品后，再加入购物车！！", '<h4>友情提示：</h4>');
		}
		return false;
	});
	$('#orderFormShopping').parent().on('hidden', function() {
		if ($("#shoppingModal").html() !== "") {
			$("#shoppingModal").dialog('destroy');
		};
	});
	$('#orderFormShopping').parent().on('shown', function() {
		//判断客户姓名有没有内容
		if($("#shoppingName").val()==null && $(this).attr("tid")=="Zero"){
			toastr.error("暂无消费客户记录", '<h4>错误提示：</h4>');
			$("#orderFormShopping").parent().modal('hide');
		};
		//判断是否隐藏客户姓名
		if($(this).attr("dataid")=="undefined"){
			if($(this).attr("valHide")=="snap"){
				$("#hideShoppingName").addClass("hide");
			}else{
				$("#hideShoppingName").removeClass("hide");
			};
		}else{
			$("#hideShoppingName").addClass("hide");
		};
	});
	$("#submitBTN").on("click", function() {
		$.ajax({
			url: "/Handler/OrderHandler.ashx",
			type: "post",
			data: {
				fun: "f_0001",
				Type_ID: $("#Type_ID").val(),
				Type_Name: $("#Type_ID option:checked").text()
			},
			beforeSend: function() {
				//数据加载冻屏
				$("#submitBTN").button('loading');
			},
			success: function(msg) {
				//数据加载完毕解除冻屏
				$("#submitBTN").button('reset');
				if (msg !== "") {
					$("#tableBODY").html(msg);
					//勾选checkbox事件
					$.each($("#type" + $("#Type_ID").val()).val().split(","), function(n1, v1) {
						$("#tableBODY .shopCheck").each(function(n2, v2) {
							if (v1 === $(v2).val()) {
								$(v2).prop("checked", true);
							};
						});
					});
					//表格checkbox框点击事件
					$("#tableBODY .shopCheck").on("click", function() {
						var p_code = "",
							p_name = "",
							p_value = "",
							p_select = "",
							p_money = "";
						var typeid = $(this).attr("vid"); //获得隐藏input传值框id
						if ($("#tableBODY .shopCheck:checked").length === 0) {
							$("#" + typeid).val(""); //如果表格中没有选中checkbox，input传值框为空
						} else {
							//如果表格有选中checkbox，循环选中的项目
							$("#tableBODY .shopCheck:checked").each(function() {
								//组装数据
								p_code += $(this).parents("tr").find(".Product_Code").text() + ",";
								p_name += $(this).parents("tr").find(".Product_Name").text() + ",";
								p_value += $(this).val() + ",";
								p_select = $(this).attr("val1");
								p_money += $(this).parents("tr").find(".Product_Money").val() + ",";
								//为input传值框赋值
								$("#" + typeid).val(p_value.substr(0, p_value.length - 1));
								//为input传值框附加属性值
								$("#" + typeid).data("datalist", {
									code: p_code.substr(0, p_code.length - 1),
									name: p_name.substr(0, p_name.length - 1),
									select: p_select,
									money: p_money.substr(0, p_money.length - 1)
								});
							});
						};
					});
					
					//表格dataTable
					$('#tableBODY table').dataTable({
						"bJQueryUI": true,
						"sPaginationType": "full_numbers",
						"sDom": '<""l>t<"F"fp>',
						"oLanguage": {
					      "oPaginate": {
					      	"sPrevious": "上一页",
					        "sNext": "下一页",
					        "sLast": "末页",
					        "sFirst": "首页",
					        "sZeroRecords": "No records to display"
					      },
					      "sEmptyTable" :"没有可用数据表",
					      "sSearch": "搜索：",
					      "sLengthMenu": '每页显示 <select>'+
					        '<option value="10">10</option>'+
					        '<option value="20">20</option>'+
					        '<option value="30">30</option>'+
					        '<option value="50">50</option>'+
					        '</select> 条记录'
					    }
					});
					$('#tableBODY select').select2();
				} else {
					toastr.error(msg, '错误提示：');
				}
			}
		});
	}).trigger("click");
	
});